<template>
  <!-- 外层容器，使用略大的裁剪形状，负责显示白色边框 -->
  <div class="navbar-outer-container relative">
    <!-- 内层容器，使用原始裁剪形状，负责显示内容 -->
    <div class="bg-primary navbar-container relative">
      <div class="m-auto flex justify-between items-center md:w-[1440px] md:h-[100px] md:mt-1 w-[350px] h-[24px] mt-1 mb-1 pb-4">
        <div class="flex items-center ml-12">
          <img class="w-[142px] h-[32px] md:w-[142px] md:h-[32px]" fit="cover" src="@/assets/images/logo-img.png" />
          <!-- <span class="text-[16px] ml-[6px] md:ml-2 md:text-xl font-medium text-primary">veteer</span> -->
        </div>
        <div class="text-white text-[16px] font-medium hidden md:block hover:cursor-pointer text-right">
          <ul class="flex justify-evenly pd-3 nav-menu-container">
            <template v-for="(item, index) in navList" :key="index">
              <li class="mx-4 nav-item" :data="index" @click="handleMenuClick(item, 1)"
                :class="currentKey === index ? 'nav-item-active nav-item-active-text' : ''">
                {{ $t(`base.nav.${item.name}`) }}
              </li>
            </template>
          </ul>
        </div>
        <div>
          <!-- <div class="flex flex-col items-center md:items-center md:flex-row">
            <button @click="handleLogin" :class="currentKey == 0 ? 'bg-bgColorDark' : 'bg-white'"
              class="w-[90px] h-[30px] rounded-[15px] border border-primary text-sm text-primary font-medium hidden md:block">
              {{ $t('base.login.text') }}
            </button> -->
            <!-- 国际化 -->
            <!-- <div class="md:ml-4 hidden md:block">
              <a-dropdown trigger="hover" @select="handleDropdown">
                <a-button size="small">{{ currentLanguage }} <icon-caret-down class="ml-1" /></a-button>
                <template #content>
                  <a-doption v-for="(item, index) in supportedLocales" :key="index">{{ item.label }}</a-doption>
                </template>
              </a-dropdown>
            </div> -->
            <!-- 深色模式/日间模式 -->
            <!-- <div class="absolute top-10 right-2 md:top-0 md:right-0 md:ml-4 md:relative">
              <a-switch size="medium" :default-checked="false" :model-value="switchTheme" @change="handleSwitchTheme"
                :checked-value="true" :unchecked-value="false" checked-color="#000033">
                <template #checked-icon>
                  <icon-moon />
                </template>
                <template #unchecked-icon>
                  <icon-sun />
                </template>
              </a-switch>
            </div>
          </div> -->
          <!-- 汉堡菜单 -->
          <div class="block md:hidden" @click="handleShowMenu">
            <a-space size="large">
              <icon-menu :style="{ fontSize: '16px', color: currentKey == 0 ? '#fff' : '#000' }" />
            </a-space>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 移动设备下左侧菜单 -->
  <a-drawer :width="340" :height="340" :visible="visible" :hideCancel="true" :header="true" :footer="false"
    :placement="'left'" class="relative" @ok="handleOk" @cancel="handleCancel" unmountOnClose>
    <template #title>
      <span class="text-[16px] ml-[6px] font-medium text-primary">Insurance</span>
    </template>
    <div>
      <ul class="flex justify-evenly flex-col">
        <template v-for="(item, index) in navList" :key="index">
          <li class="mt-[48px] nav-item ml-1 h-[24px] leading-[24px]" :data="index" @click="handleMenuClick(item, 2)"
            :class="currentKey === index ? 'nav-item-active-h5 nav-item-active-text ' : ''">
            {{ $t(`base.nav.${item.name}`) }}
          </li>
        </template>
      </ul>
    </div>
    <div class="absolute left-4 bottom-6">
      <button @click="handleLogin"
        class="w-[82px] h-[36px] rounded-[15px] border border-primary text-sm text-primary font-medium">
        {{ $t('base.login.text') }}
      </button>
    </div>
    <div class="absolute right-4 bottom-6">
      <a-dropdown trigger="hover" @select="handleDropdown">
        <a-button size="small">{{ currentLanguage }} <icon-caret-down class="ml-1" /></a-button>
        <template #content>
          <a-doption v-for="(item, index) in supportedLocales" :key="index">{{ item.label }}</a-doption>
        </template>
      </a-dropdown>
    </div>
  </a-drawer>
  
  <!-- 登录弹窗 -->
  <LoginModal 
    v-model:visible="showLoginModal" 
    @login-success="handleLoginSuccess" 
  />
</template>
<script setup lang="ts">
import { IconMenu } from '@arco-design/web-vue/es/icon'
import { computed, onMounted, reactive, ref, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useUserStore } from '@/stores/user'
import LoginModal from './LoginModal.vue'
import { Message } from '@arco-design/web-vue'
import type { Locale } from 'vue-i18n'

const route = useRouter()
const userStore = useUserStore()
const currentKey = ref(0)
const switchTheme = ref(false)
const showLoginModal = ref(false)

// 暗色模式切换
const handleSwitchTheme = (ev: Event) => {
  switchTheme.value = !switchTheme.value
  if (switchTheme.value) {
    // 设置为暗黑主题
    document.body.setAttribute('arco-theme', 'dark')
    console.log(ev)
  } else {
    // 设置为明亮主题
    document.body.setAttribute('arco-theme', 'light')
  }
}
// 修改 navList 中的路径
const navList = reactive([
  {
    id: 0,
    name: 'News',
    path: '/news', // 修改路径，去掉 /layout
  },
  {
    id: 1,
    name: 'Events',
    path: '/events', // 修改路径，去掉 /layout
  },
  {
    id: 2,
    name: 'Cases',
    path: '/cases', // 修改路径，去掉 /layout
  },
  {
    id: 3,
    name: 'Forums',
    path: '/faq', // 修改路径，去掉 /layout
  },
  {
    id: 4,
    name: 'UserCenter',
    path: '/user/center', // 修改路径，去掉 /layout
  },
  {
    id: 5,
    name: 'ContactUs',
    path: '/contact', // 修改路径，去掉 /layout
  },
])
const visible = ref(false)
const handleShowMenu = () => {
  console.log('click')
  visible.value = true
}
const handleOk = () => {
  visible.value = false
}
const handleCancel = () => {
  visible.value = false
}
//点击nav时
const handleMenuClick = (e: any, type: number) => {
  // 检查是否需要登录验证的页面
  const needAuthPages = ['/faq', '/user/center'] // Forums 和 User Center
  
  if (needAuthPages.includes(e.path)) {
    // 检查用户是否已登录
    if (!userStore.isLoggedIn) {
      // 直接弹出登录窗口，不显示警告信息
      showLoginModal.value = true
      return
    }
  }
  
  if (type === 2) {
    currentKey.value = e.id
    visible.value = false
    route.push(e.path)
  } else {
    currentKey.value = e.id
    route.push(e.path)
  }
}

// 登录成功后的处理
const handleLoginSuccess = () => {
  Message.success('登录成功，欢迎回来！')
  // 可以在这里添加其他登录成功后的逻辑
}

// 组件挂载时检查登录状态
onMounted(async () => {
})

//登录
const handleLogin = () => {
  route.push('/login')
}

// 获取i18n实例
const { locale } = useI18n()
// 支持的语言列表（带类型校验）
type SupportedLocale = {
  value: Locale
  label: string
}
const supportedLocales = ref<SupportedLocale[]>([
  { value: 'zh-cn', label: '简体中文' },
  { value: 'en', label: 'English' },
])
// 当前语言状态（带本地存储持久化）
const currentLocale = ref<Locale>(
  (() => {
    // 从本地存储读取或回退默认
    const savedLang = localStorage.getItem('user_lang') as Locale | null
    return savedLang || 'en'
  })()
)
//初始化同步
watchEffect(() => {
  locale.value = currentLocale.value
})

const currentLanguage = ref(currentLocale.value === 'zh-cn' ? '简体中文' : 'English')
//切换语言
const handleDropdown = async (e: any) => {
  currentLanguage.value = e
  if (e === '简体中文') {
    currentLocale.value = 'zh-cn'
    localStorage.setItem('user_lang', 'zh-cn')
  } else {
    currentLocale.value = 'en'
    localStorage.setItem('user_lang', 'en')
  }
}

onMounted(() => {
  // 获取当前路由，如果路由包含"/news"，那么导航栏就选中News
  const currentPath = route.currentRoute.value.path
  
  // 查找匹配的导航项
  const matchedNavItem = navList.find(item => {
    // 检查当前路径是否包含导航项的路径
    // 对于news路径特殊处理
    if (item.name === 'News' && currentPath.includes('/news')) {
      return true
    }
    // 其他导航项精确匹配
    return currentPath === item.path
  })
  
  // 如果找到匹配项，设置当前选中的导航项
  if (matchedNavItem) {
    currentKey.value = matchedNavItem.id
  }
})
</script>

<style scoped>
/* 外层容器样式 */
.navbar-outer-container {
  position: relative;
  background-color: white; /* 白色背景作为边框 */
  /* 外层容器也被裁剪，但裁剪形状比内层略大 */
  clip-path: polygon(
    0 0,
    100% 0,
    100% 80%,
    28% 80%,
    27.5% 100%,
    26% 60%,
    25.5% 80%,
    25% 80%,
    0 80%
  );
  width: 100%;
  overflow: visible;
}

/* 内层容器样式 */
.navbar-container {
  overflow: visible;
  clip-path: polygon(
    0 0,
    100% 0,
    100% 80%,
    28% 80%,
    27.5% 100%,
    26% 60%,
    25.5% 80%,
    25% 80%,
    0 80%
  ); /* 创建心电图式波浪底部 */
  position: relative;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.nav-menu-container {
  border: 2px solid #FFFFFF;
  border-radius: 17px;
  padding: 8px 12px;
  /* 固定宽度和高度，防止内容变化导致容器尺寸变化 */
  min-height: 40px;
  min-width: 500px; /* 添加固定最小宽度 */
  display: flex;
  align-items: center;
  justify-content: center; /* 确保内容居中 */
  box-sizing: border-box; /* 确保边框不会增加元素尺寸 */
}

.nav-item {
  @apply relative;
  font-size: 16px;
  font-weight: 500;
  padding: 4px 8px;
  transition: all 0.3s ease;
  /* 固定宽度和高度，防止字体大小变化导致尺寸变化 */
  height: 28px;
  min-width: 60px; /* 添加最小宽度 */
  display: flex;
  align-items: center;
  justify-content: center; /* 确保文本居中 */
  box-sizing: border-box; /* 确保内边距不会增加元素尺寸 */
}

.nav-item:hover {
  color: #e0e0e0;
}

/* 修改nav-item-active样式，去掉下划线 */
.nav-item-active {
  position: relative;
  /* 可以添加其他视觉效果，如背景色等 */
}

/* 删除下划线样式 */
/* .nav-item-active::before {
  content: '';
  @apply absolute -bottom-[6px] h-[2px] w-full bg-white opacity-100 transition-all;
} */

.nav-item-active-h5::before {
  content: '';
  @apply absolute -left-1 w-[2px] h-[24px] bg-primary opacity-100 transition-all;
}

.nav-item-active-text {
  @apply text-white;
  font-size: 18px;
  font-weight: 600;
}
</style>
